package com.srs.backend.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import com.srs.backend.mapper.*;
import com.srs.backend.pojo.*;
import com.srs.backend.service.FoodService;
import com.srs.backend.service.FoodStyleService;
import com.srs.backend.service.MaterialService;
import com.srs.backend.utils.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FoodServiceImpl implements FoodService {
    @Resource
    private FoodMapper foodMapper;
    @Resource
    private FoodStyleMapper foodStyleMapper;
    @Resource
    private FoodMaterialMapper foodMaterialMapper;
    @Resource
    private MaterialMapper materialMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private ChefMapper chefMapper;

    @Override
    public Result add(Map<String, String> data) {
        String name = data.get("name");
        String foodStyleIdStr = data.get("food_style_id");
        Integer foodStyleId = null;
        String priceStr = data.get("price");
        Double price = null;
        String remark = data.get("remark");

        try {
            foodStyleId = Integer.parseInt(foodStyleIdStr);
            price = Double.parseDouble(priceStr);
        } catch (NumberFormatException e) {
            return Result.error("数据类型错误");
        }

        if (name == null || name.length() == 0) {
            return Result.error("食物名称不能为空");
        }

        if (name.length() > 20) {
            return Result.error("食物名称过长");
        }

        foodMapper.insert(new Food(null, name, foodStyleId, price, remark));

        return Result.ok("success");
    }

    @Override
    public Result delete(Map<String, String> data) {
        String idStr = data.get("id");
        Integer id = null;
        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            return Result.error("id数据有误");
        }
        Food curFood = foodMapper.selectById(id);
        if (curFood == null) {
            return Result.error("当前操作菜品不存在或已被删除");
        }
        foodMapper.deleteById(curFood);

        // 菜品删除后，对应的 菜品-原材料 的关系也要删除
        QueryWrapper<FoodMaterial> foodMaterialQueryWrapper = new QueryWrapper<>();
        foodMaterialQueryWrapper.eq("food_id", id);
        List<FoodMaterial> foodMaterials = foodMaterialMapper.selectList(foodMaterialQueryWrapper);

        for (int i = 0; i < foodMaterials.size(); i ++ ) {
            foodMaterialMapper.deleteById(foodMaterials.get(i));
        }

        return Result.ok("success");
    }

    @Override
    public Result modify(Map<String, String> data) {
        String idStr = data.get("id");
        Integer id = null;
        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            return Result.error("id数据有误");
        }
        Food curFood = foodMapper.selectById(id);
        if (curFood == null) {
            return Result.error("当前操作菜品不存在或已被删除");
        }

        String name = data.get("name");
        String foodStyleIdStr = data.get("food_style_id");
        Integer foodStyleId = null;
        String priceStr = data.get("price");
        Double price = null;
        String remark = data.get("remark");

        try {
            foodStyleId = Integer.parseInt(foodStyleIdStr);
            price = Double.parseDouble(priceStr);
        } catch (NumberFormatException e) {
            return Result.error("数据类型错误");
        }

        if (name == null || name.length() == 0) {
            return Result.error("食物名称不能为空");
        }

        if (name.length() > 20) {
            return Result.error("食物名称过长");
        }

        curFood.setName(name);
        curFood.setFoodStyleId(foodStyleId);
        curFood.setPrice(price);
        curFood.setRemark(remark);

        foodMapper.updateById(curFood);
        return Result.ok("success");
    }

    @Override
    public Result getAll() {
        List<Food> foods = foodMapper.selectList(null);
        for (int i = 0; i < foods.size(); i ++ ) {
            if (foods.get(i).getFoodStyleId() != null) {
                FoodStyle curFoodStyle = foodStyleMapper.selectById(foods.get(i).getFoodStyleId());
                foods.get(i).setFoodStyleName(curFoodStyle.getName());
            }
        }
        return Result.ok(foods);
    }

    // 获取所有可生产的菜品（库存原材料数量>=制作所需原材料数量）
    @Override
    public Result getAllProducibleFood() {
        List<Food> foodList = foodMapper.selectList(null);

        List<Food> res = new LinkedList<>();

        for (int i = 0; i < foodList.size(); i ++ ) {
            boolean flag = true;
            Food food = foodList.get(i);
            QueryWrapper<FoodMaterial> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("food_id", food.getId());
            List<FoodMaterial> foodMaterials = foodMaterialMapper.selectList(queryWrapper);
            for (int j = 0; j < foodMaterials.size(); j ++ ) {
                FoodMaterial foodMaterial = foodMaterials.get(j);
                Material material = materialMapper.selectById(foodMaterial.getMaterialId());
                if (material.getNum() < foodMaterial.getMaterialNum()) {
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                if (food.getFoodStyleId() != null) {
                    FoodStyle curFoodStyle = foodStyleMapper.selectById(food.getFoodStyleId());
                    food.setFoodStyleName(curFoodStyle.getName());
                }
                res.add(food);
            }
        }

        return Result.ok(res);
    }

    // 通过订单获取订单所对应的所有菜品
    @Override
    public Result getFoodByOrderId(Map<String, String> data) {
        String orderIdStr = data.get("order_id");
        Integer orderId;
        try {
            orderId = Integer.parseInt(orderIdStr);
        } catch (Exception e) {
            return Result.error("数据类型有误");
        }
        Orders orders = orderMapper.selectById(orderId);
        if (orders == null) {
            return Result.error("该订单不存在或已被删除");
        }
        QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
        orderItemQueryWrapper.eq("order_id", orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemQueryWrapper);
        List<Food> foodList = new LinkedList<>();
        for (int i = 0; i < orderItemList.size(); i ++ ) {
            Integer fId = orderItemList.get(i).getFoodId();
            boolean flag = true;
            for (int j = 0; j < foodList.size(); j ++ ) {
                if (foodList.get(j).getId() == fId) {
                    foodList.get(j).setNum(foodList.get(j).getNum() + 1);
                    flag = false;
                    break;
                }
            }
            if (flag) {
                Food newFood = foodMapper.selectById(fId);
                newFood.setNum(1);
                foodList.add(newFood);
            }
        }

        return Result.ok(foodList);
    }

    // 根据时间段生成厨师制作的菜品的数量
    @Override
    public Result getChefAllDoneByPeriod(Map<String, String> data) {
        String chefIdStr = data.get("chef_id");
        String startTimeStr = data.get("start_time");
        String endTimeStr = data.get("end_time");
        Integer chefId;
        Date startTime, endTime;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            chefId = Integer.parseInt(chefIdStr);
            startTime = dateFormat.parse(startTimeStr);
            endTime = dateFormat.parse(endTimeStr);
        } catch (Exception e) {
            return Result.error("日期格式有误或厨师id数据类型有误");
        }
        Chef chef = chefMapper.selectById(chefId);
        if (chef == null) {
            return Result.error("该厨师不存在或已被删除");
        }
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chef_id", chefId);
        queryWrapper.ge("finish_time", startTime);
        queryWrapper.le("finish_time", endTime);
        List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);
        return Result.ok(orderItems.size());
    }
}
